package com.yhy.wxzn.wcs.device.plc.task;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.yhy.wxzn.common.utils.DateUtil;
import com.yhy.wxzn.common.utils.SpringUtil;
import com.yhy.wxzn.common.utils.WcsUtils;
import com.yhy.wxzn.wcs.SystemInit;
import com.yhy.wxzn.wcs.device.plc.bean.BasePlc;
import com.yhy.wxzn.wcs.device.plc.bean.PortPlc;
import com.yhy.wxzn.wcs.device.plc.bean.XJPHoistPlc;
import com.yhy.wxzn.wcs.device.plc.bean.XJPTransmissionPlc;
import com.yhy.wxzn.wcs.device.plc.xj.XjPlcDriver;
import com.yhy.wxzn.wcs.device.scanner.BarcodeScannerClient;
import com.yhy.wxzn.wcs.entity.WcsPort;
import com.yhy.wxzn.wcs.enums.MessageTitle;
import com.yhy.wxzn.wcs.wcsWmsCommunication.ToWms;
import com.yhy.wxzn.wcs.wcsWmsCommunication.ToWmsImpl;
import com.yhy.wxzn.wcs.wcsWmsCommunication.bean.TaskApply;
import com.yhy.wxzn.wcs.wcsWmsCommunication.bean.WcsProperties;
import com.yhy.wxzn.wcs.wcsWmsCommunication.bean.WmsResponses;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.dto.message.MessageDTO;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.system.service.impl.SysBaseApiImpl;

import java.util.Date;

import static com.yhy.wxzn.wcs.SystemInit.nameToBasePlc;
import static com.yhy.wxzn.wcs.SystemInit.transmissionDriverMap;

@Slf4j
public class InPortTaskThread extends Thread{

    private ToWms toWms = SpringUtil.getBean(ToWmsImpl.class);

    private SysBaseApiImpl sysBaseApi =  SpringUtil.getBean(SysBaseApiImpl.class);


    private WcsPort port;

    public InPortTaskThread(WcsPort port){
        super(port.getPortName()+"库口线程");
        this.port = port;
    }

    private void process() {
        String code = "";
        int height = 0;
        double weight = 0;


        BasePlc basePlc = nameToBasePlc.get("输送线1");

        int startScan = 0;
        if (basePlc!= null){
            XJPTransmissionPlc transmissionPlc = (XJPTransmissionPlc) basePlc;
             startScan = transmissionPlc.getStartScan();
        }

        if (startScan != 1) return;

        if(StrUtil.isEmpty(port.getScanName()) && StrUtil.isEmpty(port.getShapeName()) && StrUtil.isEmpty(port.getWeightName())) return;
        XjPlcDriver xjPlcDriver = transmissionDriverMap.get(Integer.valueOf(basePlc.getDeviceId()));

        if (StrUtil.isNotEmpty(port.getScanName()) ) {
            code = readScanner();

            if (StrUtil.isEmpty(code)){
                xjPlcDriver.write("HD5015",2);
                log.info("{}扫码失败",port.getPortName());
                return;
            }else {
                xjPlcDriver.write("HD5015",1);
                log.info("{}扫码成功，code:{}",port.getPortName(),code);
            }
        }


        if (StrUtil.isNotEmpty(port.getShapeName()) && (height = readShape()) != 1 ) return;
        if (StrUtil.isNotEmpty(port.getWeightName()) && (weight = readWeight()) == 0) return;


        TaskApply taskApply = new TaskApply(
                DateUtil.format(new Date(), DateUtil.YMDHMS)
                ,port.getPortcCode()
                ,code
                ,height
                ,weight
        );


        WmsResponses wmsResponses = toWms.exeTaskApply(taskApply);


        checkWmsResponses(taskApply,wmsResponses,xjPlcDriver);

    }

    private void checkWmsResponses(TaskApply taskApply, WmsResponses wmsResponses, XjPlcDriver xjPlcDriver) {
        Integer returnStatus = wmsResponses.getReturnStatus();
        Date msgTime = wmsResponses.getMsgTime();
        String returnInfoFromWms = wmsResponses.getReturnInfo();
        if ( wmsResponses.getReturnStatus() == WcsProperties.SUCCESS){
            log.info("入库任务申请，任务库口:" + taskApply.getFromPort() + " 托盘码：" + taskApply.getBarCode() + " 的任务申请成功！ 时间-->"
                    + msgTime);

        }else if (returnStatus == WcsProperties.FAIL) {
            String msg = "入库任务申请，任务库口:" + taskApply.getFromPort() + " 托盘码：" + taskApply.getBarCode() + " 的任务申请失败！原因-->"
                    + returnInfoFromWms + " 时间-->"
                    + msgTime;
            log.error(msg);

            sendMessage(MessageTitle.APPLY_WMS,msg);
            //回退
            xjPlcDriver.write("HD5015",2);


        } else {
            String msg = "入库任务申请，状态码不存在,接收到为！" + returnStatus;
            log.error(msg);
            sendMessage(MessageTitle.APPLY_WMS,msg);
            //回退
            xjPlcDriver.write("HD5015",2);
        }
    }

    private int readShape() {
        PortPlc portPlc = (PortPlc) SystemInit.nameToBasePlc.get(port.getShapeName());

        int detection = portPlc.getDetection();

        if (detection!=1 && detection!=0){
            String s = PortPlc.ParseDetection(detection);
            sendMessage(MessageTitle.IN_PORT,port.getPortName() +"外形检测异常，原因是:"+s);
            //发送消息给wms

        }


        return detection;
    }

    private double readWeight() {

        return 0;
    }

    private String readScanner() {
        BarcodeScannerClient barcodeScannerClient = BarcodeScannerClient.deviceNameToBarcodeScannerClient.get(port.getScanName());

        return barcodeScannerClient.getBarCode();
    }

    private void sendMessage(MessageTitle messageTitle,String msg) {
        MessageDTO msgDto = new MessageDTO();
        msgDto.setFromUser("system");
        msgDto.setToUser("admin");
        msgDto.setContent(msg);
        msgDto.setTitle(messageTitle.getDescription());
        sysBaseApi.sendSysAnnouncement(msgDto);
    }


    @Override
    public void run() {
        while (true){
            try {
                process();
            }catch (Exception e){
                log.error(e.getMessage(),e);
            }
            WcsUtils.sleep(1000);
        }

    }


}
